System.Collections.Generic.List<T> クラス

この記事では、この API のリファレンス ドキュメントへの補足的な解説を提供します。

クラスは List<T> 、クラスに相当する ArrayList ジェネリックです。 必要に応じてサイズが IList<T> 動的に増加する配列を使用して、ジェネリック インターフェイスを実装します。

またはAddRangeメソッドを使用して、項目を a List<T>Add追加できます。

クラスでは List<T> 、等価比較子と順序比較子の両方が使用されます。

  • 、 などのContainsIndexOfLastIndexOfメソッドでRemove、リスト要素に等値比較子を使用します。 型 T の既定の等値比較子は、次のように決定されます。 型 T がジェネリック インターフェイスを IEquatable<T> 実装する場合、等値比較子はそのインターフェイスのメソッドです Equals(T) 。それ以外の場合、既定の等値比較子は Object.Equals(Object).

  • リスト要素の順序付け比較子などの BinarySearch メソッドと Sort 使用します。 型 T の既定の比較子は、次のように決定されます。 型 T がジェネリック インターフェイスを IComparable<T> 実装する場合、既定の比較子はその CompareTo(T) インターフェイスのメソッドです。それ以外の場合、型 T が非ジェネリック IComparable インターフェイスを実装する場合、既定の比較子はそのインターフェイスのメソッドになります CompareTo(Object) 。 型 T でどちらのインターフェイスも実装されていない場合、既定の比較子はなく、比較子または比較デリゲートを明示的に指定する必要があります。

List<T> べ替えが保証されるわけではありません。 並べ替えを List<T> 必要とする操作 (など BinarySearch) を実行する前に List<T> 並べ替える必要があります。

このコレクション内の要素には、整数インデックスを使用してアクセスできます。 このコレクション内のインデックスは 0 から始まります。

.NET Framework のみ: 非常に大きなList<T>オブジェクトの場合、構成要素の属性<gcAllowVeryLargeObjects>を実行時環境に設定enabledすることで、64 ビット システムで最大容量を 20 億要素にtrue増やすことができます。

List<T> は参照型の null 有効な値として受け取り、重複する要素を許可します。

クラスの変更できないバージョンについては、次を List<T> 参照してください ImmutableList<T>

パフォーマンスに関する考慮事項

どちらの機能も同様の機能を List<T> 持つクラスを ArrayList 使用するかどうかを決定する際には、ほとんどの場合、クラスの List<T> パフォーマンスが向上し、型セーフであることを覚えておいてください。 クラスの型に参照型を使用 T する List<T> 場合、2 つのクラスの動作は同じです。 ただし、型に値型を使用する T場合は、実装とボックス化の問題を考慮する必要があります。

型に値型が使用されている T場合、コンパイラは、その値型専用のクラスの List<T> 実装を生成します。 つまり、オブジェクトの List<T> リスト要素は、要素を使用する前にボックス化する必要はありません。また、約 500 個のリスト要素が作成された後、リスト要素をボックス化しないことによって保存されるメモリは、クラス実装の生成に使用されるメモリよりも大きくなります。

T に使用される値型がジェネリック インターフェイスを IEquatable<T> 実装していることを確認します。 そうでない場合、メソッドなどの Contains メソッドは、影響を受けるリスト要素を Object.Equals(Object) ボックス化するメソッドを呼び出す必要があります。 値型がインターフェイスをIComparable実装し、ソース コードを所有している場合は、ジェネリック インターフェイスも実装IComparable<T>して、リスト要素とSortメソッドがボックス化されないようにBinarySearchします。 ソース コードを所有していない場合は、オブジェクトをIComparer<T>メソッドSortBinarySearch渡します。

クラスを使用したり、厳密に型指定されたラッパー コレクションを自分で記述したりする代わりに、クラスのArrayList型固有の実装List<T>を使用することが利点です。 これは、実装で .NET が既に行っていることを行う必要があり、.NET ランタイムが共通の中間言語コードとメタデータを共有できるためです。これは、実装では共有できません。

F# に関する考慮事項

この List<T> クラスは、F# コードであまり使用しません。 代わりに、変更できない、1 つのリンクされたリストであるリストが一般的に推奨されます。 F# List は順序付けされた不変の一連の値を提供し、機能スタイルの開発で使用するためにサポートされています。 F# から使用する場合、F# リストとの名前付けの競合を回避するために、 List<T> クラスは通常、型の省略形によって ResizeArray<'T> 参照されます。

次の例では、単純なビジネス オブジェクトを追加、削除、および挿入する方法を List<T>示します。

using System;
using System.Collections.Generic;

// Simple business object. A PartId is used to identify the type of part
// but the part name can change.
public class Part : IEquatable<Part>
{
    public string PartName { get; set; }

    public int PartId { get; set; }

    public override string ToString()
    {
        return "ID: " + PartId + "   Name: " + PartName;
    }
    public override bool Equals(object obj)
    {
        if (obj == null) return false;
        Part objAsPart = obj as Part;
        if (objAsPart == null) return false;
        else return Equals(objAsPart);
    }
    public override int GetHashCode()
    {
        return PartId;
    }
    public bool Equals(Part other)
    {
        if (other == null) return false;
        return (this.PartId.Equals(other.PartId));
    }
    // Should also override == and != operators.
}

public class Example
{
    public static void Main()
    {
        // Create a list of parts.
        List<Part> parts =
        [
            // Add parts to the list.
            new Part() { PartName = "crank arm", PartId = 1234 },
            new Part() { PartName = "chain ring", PartId = 1334 },
            new Part() { PartName = "regular seat", PartId = 1434 },
            new Part() { PartName = "banana seat", PartId = 1444 },
            new Part() { PartName = "cassette", PartId = 1534 },
            new Part() { PartName = "shift lever", PartId = 1634 },
        ];

        // Write out the parts in the list. This will call the overridden ToString method
        // in the Part class.
        Console.WriteLine();
        foreach (Part aPart in parts)
        {
            Console.WriteLine(aPart);
        }

        // Check the list for part #1734. This calls the IEquatable.Equals method
        // of the Part class, which checks the PartId for equality.
        Console.WriteLine("\nContains(\"1734\"): {0}",
        parts.Contains(new Part { PartId = 1734, PartName = "" }));

        // Insert a new item at position 2.
        Console.WriteLine("\nInsert(2, \"1834\")");
        parts.Insert(2, new Part() { PartName = "brake lever", PartId = 1834 });

        //Console.WriteLine();
        foreach (Part aPart in parts)
        {
            Console.WriteLine(aPart);
        }

        Console.WriteLine("\nParts[3]: {0}", parts[3]);

        Console.WriteLine("\nRemove(\"1534\")");

        // This will remove part 1534 even though the PartName is different,
        // because the Equals method only checks PartId for equality.
        parts.Remove(new Part() { PartId = 1534, PartName = "cogs" });

        Console.WriteLine();
        foreach (Part aPart in parts)
        {
            Console.WriteLine(aPart);
        }
        Console.WriteLine("\nRemoveAt(3)");
        // This will remove the part at index 3.
        parts.RemoveAt(3);

        Console.WriteLine();
        foreach (Part aPart in parts)
        {
            Console.WriteLine(aPart);
        }

        /*

         ID: 1234   Name: crank arm
         ID: 1334   Name: chain ring
         ID: 1434   Name: regular seat
         ID: 1444   Name: banana seat
         ID: 1534   Name: cassette
         ID: 1634   Name: shift lever

         Contains("1734"): False

         Insert(2, "1834")
         ID: 1234   Name: crank arm
         ID: 1334   Name: chain ring
         ID: 1834   Name: brake lever
         ID: 1434   Name: regular seat
         ID: 1444   Name: banana seat
         ID: 1534   Name: cassette
         ID: 1634   Name: shift lever

         Parts[3]: ID: 1434   Name: regular seat

         Remove("1534")

         ID: 1234   Name: crank arm
         ID: 1334   Name: chain ring
         ID: 1834   Name: brake lever
         ID: 1434   Name: regular seat
         ID: 1444   Name: banana seat
         ID: 1634   Name: shift lever

         RemoveAt(3)

         ID: 1234   Name: crank arm
         ID: 1334   Name: chain ring
         ID: 1834   Name: brake lever
         ID: 1444   Name: banana seat
         ID: 1634   Name: shift lever


     */
    }
}

' Simple business object. A PartId is used to identify the type of part 
' but the part name can change. 
Public Class Part
    Implements IEquatable(Of Part)
    Public Property PartName() As String
        Get
            Return m_PartName
        End Get
        Set(value As String)
            m_PartName = value
        End Set
    End Property
    Private m_PartName As String

    Public Property PartId() As Integer
        Get
            Return m_PartId
        End Get
        Set(value As Integer)
            m_PartId = value
        End Set
    End Property
    Private m_PartId As Integer

    Public Overrides Function ToString() As String
        Return "ID: " & PartId & "   Name: " & PartName
    End Function
    Public Overrides Function Equals(obj As Object) As Boolean
        If obj Is Nothing Then
            Return False
        End If
        Dim objAsPart As Part = TryCast(obj, Part)
        If objAsPart Is Nothing Then
            Return False
        Else
            Return Equals(objAsPart)
        End If
    End Function
    Public Overrides Function GetHashCode() As Integer
        Return PartId
    End Function
    Public Overloads Function Equals(other As Part) As Boolean _
        Implements IEquatable(Of Part).Equals
        If other Is Nothing Then
            Return False
        End If
        Return (Me.PartId.Equals(other.PartId))
    End Function
    ' Should also override == and != operators.

End Class
Public Class Example
    Public Shared Sub Main()
        ' Create a list of parts.
        Dim parts As New List(Of Part)()

        ' Add parts to the list.
        parts.Add(New Part() With {
             .PartName = "crank arm",
             .PartId = 1234
        })
        parts.Add(New Part() With {
             .PartName = "chain ring",
             .PartId = 1334
        })
        parts.Add(New Part() With {
             .PartName = "regular seat",
             .PartId = 1434
        })
        parts.Add(New Part() With {
             .PartName = "banana seat",
             .PartId = 1444
        })
        parts.Add(New Part() With {
             .PartName = "cassette",
             .PartId = 1534
        })
        parts.Add(New Part() With {
             .PartName = "shift lever",
             .PartId = 1634
        })



        ' Write out the parts in the list. This will call the overridden ToString method
        ' in the Part class.
        Console.WriteLine()
        For Each aPart As Part In parts
            Console.WriteLine(aPart)
        Next


        ' Check the list for part #1734. This calls the IEquatable.Equals method
        ' of the Part class, which checks the PartId for equality.
        Console.WriteLine(vbLf & "Contains(""1734""): {0}", parts.Contains(New Part() With {
             .PartId = 1734,
             .PartName = ""
        }))

        ' Insert a new item at position 2.
        Console.WriteLine(vbLf & "Insert(2, ""1834"")")
        parts.Insert(2, New Part() With {
             .PartName = "brake lever",
             .PartId = 1834
        })


        'Console.WriteLine();
        For Each aPart As Part In parts
            Console.WriteLine(aPart)
        Next

        Console.WriteLine(vbLf & "Parts[3]: {0}", parts(3))

        Console.WriteLine(vbLf & "Remove(""1534"")")

        ' This will remove part 1534 even though the PartName is different,
        ' because the Equals method only checks PartId for equality.
        parts.Remove(New Part() With {
             .PartId = 1534,
             .PartName = "cogs"
        })

        Console.WriteLine()
        For Each aPart As Part In parts
            Console.WriteLine(aPart)
        Next

        Console.WriteLine(vbLf & "RemoveAt(3)")
        ' This will remove part at index 3.
        parts.RemoveAt(3)

        Console.WriteLine()
        For Each aPart As Part In parts
            Console.WriteLine(aPart)
        Next
    End Sub
    '
    '        This example code produces the following output:
    '        ID: 1234   Name: crank arm
    '        ID: 1334   Name: chain ring
    '        ID: 1434   Name: regular seat
    '        ID: 1444   Name: banana seat
    '        ID: 1534   Name: cassette
    '        ID: 1634   Name: shift lever
    '
    '        Contains("1734"): False
    '
    '        Insert(2, "1834")
    '        ID: 1234   Name: crank arm
    '        ID: 1334   Name: chain ring
    '        ID: 1834   Name: brake lever
    '        ID: 1434   Name: regular seat
    '        ID: 1444   Name: banana seat
    '        ID: 1534   Name: cassette
    '        ID: 1634   Name: shift lever
    '
    '        Parts[3]: ID: 1434   Name: regular seat
    '
    '        Remove("1534")
    '
    '        ID: 1234   Name: crank arm
    '        ID: 1334   Name: chain ring
    '        ID: 1834   Name: brake lever
    '        ID: 1434   Name: regular seat
    '        ID: 1444   Name: banana seat
    '        ID: 1634   Name: shift lever
    '   '
    '        RemoveAt(3)
    '
    '        ID: 1234   Name: crank arm
    '        ID: 1334   Name: chain ring
    '        ID: 1834   Name: brake lever
    '        ID: 1444   Name: banana seat
    '        ID: 1634   Name: shift lever
    '        

End Class

// Simple business object. A PartId is used to identify the type of part  
// but the part name can change.  
[<CustomEquality; NoComparison>]
type Part = { PartId : int ; mutable PartName : string } with
    override this.GetHashCode() = hash this.PartId
    override this.Equals(other) =
        match other with
        | :? Part as p -> this.PartId = p.PartId
        | _ -> false
    override this.ToString() = sprintf "ID: %i   Name: %s" this.PartId this.PartName

[<EntryPoint>]
let main argv = 
    // We refer to System.Collections.Generic.List<'T> by its type 
    // abbreviation ResizeArray<'T> to avoid conflicts with the F# List module.    
    // Note: In F# code, F# linked lists are usually preferred over
    // ResizeArray<'T> when an extendable collection is required.
    let parts = ResizeArray<_>()
    parts.Add({PartName = "crank arm" ; PartId = 1234})
    parts.Add({PartName = "chain ring"; PartId = 1334 })
    parts.Add({PartName = "regular seat"; PartId = 1434 })
    parts.Add({PartName = "banana seat"; PartId = 1444 })
    parts.Add({PartName = "cassette"; PartId = 1534 })
    parts.Add({PartName = "shift lever"; PartId = 1634 })

    // Write out the parts in the ResizeArray.  This will call the overridden ToString method
    // in the Part type
    printfn ""
    parts |> Seq.iter (fun p -> printfn "%O" p)

    // Check the ResizeArray for part #1734. This calls the IEquatable.Equals method 
    // of the Part type, which checks the PartId for equality.    
    printfn "\nContains(\"1734\"): %b" (parts.Contains({PartId=1734; PartName=""}))
    
    // Insert a new item at position 2.
    printfn "\nInsert(2, \"1834\")"
    parts.Insert(2, { PartName = "brake lever"; PartId = 1834 })

    // Write out all parts
    parts |> Seq.iter (fun p -> printfn "%O" p)

    printfn "\nParts[3]: %O" parts.[3]

    printfn "\nRemove(\"1534\")"
    // This will remove part 1534 even though the PartName is different, 
    // because the Equals method only checks PartId for equality.
    // Since Remove returns true or false, we need to ignore the result
    parts.Remove({PartId=1534; PartName="cogs"}) |> ignore

    // Write out all parts
    printfn ""
    parts |> Seq.iter (fun p -> printfn "%O" p)

    printfn "\nRemoveAt(3)"
    // This will remove the part at index 3.
    parts.RemoveAt(3)

    // Write out all parts
    printfn ""
    parts |> Seq.iter (fun p -> printfn "%O" p)

    0 // return an integer exit code

次の例では、文字列型のジェネリック クラスのいくつかのプロパティとメソッドを List<T> 示します。 (複合型の List<T> 例については、メソッドを Contains 参照してください)。

パラメーターなしのコンストラクターは、既定の容量を持つ文字列の一覧を作成するために使用されます。 Capacityプロパティが表示され、メソッドをAdd使用して複数の項目を追加します。 項目が一覧表示され Capacity 、プロパティがプロパティと Count 共に再び表示され、必要に応じて容量が増加したことを示します。

この Contains メソッドは、リスト内の項目の存在をテストするために使用され、メソッド Insert はリストの中央に新しい項目を挿入するために使用され、リストの内容が再び表示されます。

既定 Item[] のプロパティ (C# のインデクサー) は項目を取得するために使用され、 Remove メソッドは前に追加した重複する項目の最初のインスタンスを削除するために使用され、内容が再び表示されます。 このメソッドは Remove 、最初に検出されたインスタンスを常に削除します。

この TrimExcess メソッドは、カウントに一致する容量を減らすために使用され Capacity 、プロパティとプロパティ Count が表示されます。 未使用の容量が合計容量の 10% 未満であった場合、リストのサイズは変更されません。

最後に、このメソッドをClear使用してリストからすべての項目を削除し、プロパティとCountプロパティをCapacity表示します。

List<string> dinosaurs = new List<string>();

Console.WriteLine("\nCapacity: {0}", dinosaurs.Capacity);

dinosaurs.Add("Tyrannosaurus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Mamenchisaurus");
dinosaurs.Add("Deinonychus");
dinosaurs.Add("Compsognathus");
Console.WriteLine();
foreach (string dinosaur in dinosaurs)
{
    Console.WriteLine(dinosaur);
}

Console.WriteLine("\nCapacity: {0}", dinosaurs.Capacity);
Console.WriteLine("Count: {0}", dinosaurs.Count);

Console.WriteLine("\nContains(\"Deinonychus\"): {0}",
    dinosaurs.Contains("Deinonychus"));

Console.WriteLine("\nInsert(2, \"Compsognathus\")");
dinosaurs.Insert(2, "Compsognathus");

Console.WriteLine();
foreach (string dinosaur in dinosaurs)
{
    Console.WriteLine(dinosaur);
}

// Shows accessing the list using the Item property.
Console.WriteLine("\ndinosaurs[3]: {0}", dinosaurs[3]);

Console.WriteLine("\nRemove(\"Compsognathus\")");
dinosaurs.Remove("Compsognathus");

Console.WriteLine();
foreach (string dinosaur in dinosaurs)
{
    Console.WriteLine(dinosaur);
}

dinosaurs.TrimExcess();
Console.WriteLine("\nTrimExcess()");
Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);
Console.WriteLine("Count: {0}", dinosaurs.Count);

dinosaurs.Clear();
Console.WriteLine("\nClear()");
Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);
Console.WriteLine("Count: {0}", dinosaurs.Count);

/* This code example produces the following output:

Capacity: 0

Tyrannosaurus
Amargasaurus
Mamenchisaurus
Deinonychus
Compsognathus

Capacity: 8
Count: 5

Contains("Deinonychus"): True

Insert(2, "Compsognathus")

Tyrannosaurus
Amargasaurus
Compsognathus
Mamenchisaurus
Deinonychus
Compsognathus

dinosaurs[3]: Mamenchisaurus

Remove("Compsognathus")

Tyrannosaurus
Amargasaurus
Mamenchisaurus
Deinonychus
Compsognathus

TrimExcess()
Capacity: 5
Count: 5

Clear()
Capacity: 5
Count: 0
 */
Public Class Example2

    Public Shared Sub Main()
        Dim dinosaurs As New List(Of String)

        Console.WriteLine(vbLf & "Capacity: {0}", dinosaurs.Capacity)

        dinosaurs.Add("Tyrannosaurus")
        dinosaurs.Add("Amargasaurus")
        dinosaurs.Add("Mamenchisaurus")
        dinosaurs.Add("Deinonychus")
        dinosaurs.Add("Compsognathus")

        Console.WriteLine()
        For Each dinosaur As String In dinosaurs
            Console.WriteLine(dinosaur)
        Next

        Console.WriteLine(vbLf & "Capacity: {0}", dinosaurs.Capacity)
        Console.WriteLine("Count: {0}", dinosaurs.Count)

        Console.WriteLine(vbLf & "Contains(""Deinonychus""): {0}",
            dinosaurs.Contains("Deinonychus"))

        Console.WriteLine(vbLf & "Insert(2, ""Compsognathus"")")
        dinosaurs.Insert(2, "Compsognathus")

        Console.WriteLine()
        For Each dinosaur As String In dinosaurs
            Console.WriteLine(dinosaur)
        Next
        ' Shows how to access the list using the Item property.
        Console.WriteLine(vbLf & "dinosaurs(3): {0}", dinosaurs(3))
        Console.WriteLine(vbLf & "Remove(""Compsognathus"")")
        dinosaurs.Remove("Compsognathus")

        Console.WriteLine()
        For Each dinosaur As String In dinosaurs
            Console.WriteLine(dinosaur)
        Next

        dinosaurs.TrimExcess()
        Console.WriteLine(vbLf & "TrimExcess()")
        Console.WriteLine("Capacity: {0}", dinosaurs.Capacity)
        Console.WriteLine("Count: {0}", dinosaurs.Count)

        dinosaurs.Clear()
        Console.WriteLine(vbLf & "Clear()")
        Console.WriteLine("Capacity: {0}", dinosaurs.Capacity)
        Console.WriteLine("Count: {0}", dinosaurs.Count)
    End Sub
End Class

' This code example produces the following output:
'
'Capacity: 0
'
'Tyrannosaurus
'Amargasaurus
'Mamenchisaurus
'Deinonychus
'Compsognathus
'
'Capacity: 8
'Count: 5
'
'Contains("Deinonychus"): True
'
'Insert(2, "Compsognathus")
'
'Tyrannosaurus
'Amargasaurus
'Compsognathus
'Mamenchisaurus
'Deinonychus
'Compsognathus
'
'dinosaurs(3): Mamenchisaurus
'
'Remove("Compsognathus")
'
'Tyrannosaurus
'Amargasaurus
'Mamenchisaurus
'Deinonychus
'Compsognathus
'
'TrimExcess()
'Capacity: 5
'Count: 5
'
'Clear()
'Capacity: 5
'Count: 0

[<EntryPoint>]
let main argv = 
    // We refer to System.Collections.Generic.List<'T> by its type 
    // abbreviation ResizeArray<'T> to avoid conflict with the List module.    
    // Note: In F# code, F# linked lists are usually preferred over
    // ResizeArray<'T> when an extendable collection is required.
    let dinosaurs = ResizeArray<_>()
 
    // Write out the dinosaurs in the ResizeArray.
    let printDinosaurs() =
        printfn ""
        dinosaurs |> Seq.iter (fun p -> printfn "%O" p) 
 
    
    printfn "\nCapacity: %i" dinosaurs.Capacity
 
    dinosaurs.Add("Tyrannosaurus")
    dinosaurs.Add("Amargasaurus")
    dinosaurs.Add("Mamenchisaurus")
    dinosaurs.Add("Deinonychus")
    dinosaurs.Add("Compsognathus")
 
    printDinosaurs()
 
    printfn "\nCapacity: %i" dinosaurs.Capacity
    printfn "Count: %i" dinosaurs.Count
 
    printfn "\nContains(\"Deinonychus\"): %b" (dinosaurs.Contains("Deinonychus"))
 
    printfn "\nInsert(2, \"Compsognathus\")"
    dinosaurs.Insert(2, "Compsognathus")
 
    printDinosaurs()
 
    // Shows accessing the list using the Item property.
    printfn "\ndinosaurs[3]: %s" dinosaurs.[3]
 
    printfn "\nRemove(\"Compsognathus\")"
    dinosaurs.Remove("Compsognathus") |> ignore
 
    printDinosaurs()
 
    dinosaurs.TrimExcess()
    printfn "\nTrimExcess()"
    printfn "Capacity: %i" dinosaurs.Capacity
    printfn "Count: %i" dinosaurs.Count
 
    dinosaurs.Clear()
    printfn "\nClear()"
    printfn "Capacity: %i" dinosaurs.Capacity
    printfn "Count: %i" dinosaurs.Count
 
    0 // return an integer exit code
 
    (* This code example produces the following output:
 
Capacity: 0
 
Tyrannosaurus
Amargasaurus
Mamenchisaurus
Deinonychus
Compsognathus
 
Capacity: 8
Count: 5
 
Contains("Deinonychus"): true
 
Insert(2, "Compsognathus")
 
Tyrannosaurus
Amargasaurus
Compsognathus
Mamenchisaurus
Deinonychus
Compsognathus
 
dinosaurs[3]: Mamenchisaurus
 
Remove("Compsognathus")
 
Tyrannosaurus
Amargasaurus
Mamenchisaurus
Deinonychus
Compsognathus
 
TrimExcess()
Capacity: 5
Count: 5
 
Clear()
Capacity: 5
Count: 0
    *)